

package com.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.dao.LearningProgressDao;
import com.entity.CourseEntity;
import com.entity.LearningProgressEntity;
import com.entity.LessonEntity;
import com.entity.OverallProgressEntity;
import com.service.CourseService;
import com.service.LearningProgressService;
import com.service.LessonService; // 需要注入LessonService来获取课时总时长
import com.service.OverallProgressService;
import com.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service("learningProgressService")
public class LearningProgressServiceImpl extends ServiceImpl<LearningProgressDao, LearningProgressEntity> implements LearningProgressService {

    @Autowired
    private LessonService lessonService; // 注入LessonService

    @Autowired
    private LearningProgressDao learningProgressDao;

    @Autowired
    private CourseService courseService;


    @Autowired
    private LearningProgressService learningProgressService;

    @Autowired
    private OverallProgressService overallProgressService;
    @Override
    public boolean updateOrSaveUserProgress(LearningProgressEntity progressEntity) {
        // 1. 根据 userId 和 lessonId 查找是否已存在进度记录
        EntityWrapper<LearningProgressEntity> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id", progressEntity.getUserId());
        wrapper.eq("lesson_id", progressEntity.getLessonId());
        LearningProgressEntity existingProgress = this.selectOne(wrapper);

        // 2. 获取课时的总时长
        LessonEntity lesson = lessonService.selectById(progressEntity.getLessonId());
        if (lesson == null || lesson.getDurationSeconds() == null || lesson.getDurationSeconds() <= 0) {
            // 如果课时不存在或没有时长，则无法计算进度，直接保存或更新秒数
            if (existingProgress != null) {
                existingProgress.setProgressSeconds(progressEntity.getProgressSeconds());
                return this.updateById(existingProgress);
            } else {
                return this.insert(progressEntity);
            }
        }
        Integer totalDuration = lesson.getDurationSeconds();

        // 3. 判断是否完成
        // 通常认为观看到95%就算完成
        boolean isCompleted = (progressEntity.getProgressSeconds() / totalDuration) >= 0.95;

        if (existingProgress != null) {
            // 如果记录已存在，则更新
            // 只在新的进度大于旧的进度时才更新，防止回退视频导致进度倒退
            if (progressEntity.getProgressSeconds() > existingProgress.getProgressSeconds()) {
                existingProgress.setProgressSeconds(progressEntity.getProgressSeconds());
            }
            // 如果之前未完成，现在完成了，则更新完成状态
            if (!existingProgress.getCompleted() && isCompleted) {
                existingProgress.setCompleted(true);
            }
            return this.updateById(existingProgress);
        } else {
            // 如果记录不存在，则创建新记录
            progressEntity.setCompleted(isCompleted);
            return this.insert(progressEntity);
        }
    }

    @Override
    public List<LearningProgressEntity> getProgressByUserId(Long userId) {
        EntityWrapper<LearningProgressEntity> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id", userId);
        return this.selectList(wrapper);
    }

    @Override
    public LearningProgressEntity getProgressByUserIdAndLessonId(Long userId, Long lessonId) {
        if (userId == null || lessonId == null) {
            return null;
        }
        LearningProgressEntity learningProgressEntity=learningProgressDao.getProgressByUserIdAndLessonIdXml(userId, lessonId);
        return learningProgressEntity;
    }


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<LearningProgressEntity> page = new Page<>(
                Integer.parseInt(params.get("page").toString()),
                Integer.parseInt(params.get("limit").toString())
        );

        page = this.selectPage(
                page,
                new EntityWrapper<LearningProgressEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<LearningProgressEntity> getProgressWithLessonInfoByUserId(Long userId) {
        return this.baseMapper.selectProgressWithLessonInfoByUserId(userId);
    }

    @Override
    public List<LearningProgressEntity> getProgressWithLessonInfoByCourseIdAndUserId(Long courseId, Long userId) {
        return this.baseMapper.selectProgressWithLessonInfoByCourseIdAndUserId(courseId, userId);
    }

    @Override
    public int deleteByLessonId(Integer lessonId) {
        EntityWrapper<LearningProgressEntity> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("lesson_id", lessonId);

        int deletedRows = this.baseMapper.delete(entityWrapper);
        return deletedRows;
    }

    @Override
    @Transactional // 确保整个操作在事务中，要么都成功，要么都失败回滚
    public void updateProgressAfterLessonVideoChange(Integer lessonId,Integer oldLessonDurationSeconds ,Integer newLessonDurationSeconds) {

        //删除视频时，newLessonDurationSeconds设置为0
        LessonEntity lesson = lessonService.selectById(lessonId);
        if (lesson == null) {
            return;
        }
        Long courseId = lesson.getCourseId();

        CourseEntity course = courseService.selectById(courseId);
        if (course != null) {
            Integer newOverallVideoLength=course.getOverallVideoLength()- oldLessonDurationSeconds+newLessonDurationSeconds;
            course.setOverallVideoLength(Math.max(0,newOverallVideoLength));
            //调整课程总时长
            courseService.updateById(course);
        } else {
            System.err.println("Warning: Course not found for lessonId: " + lessonId);
        }


        EntityWrapper<LearningProgressEntity> learningProgressWrapper = new EntityWrapper<>();
        learningProgressWrapper.eq("lesson_id", lessonId);
        List<LearningProgressEntity> learningProgressList = learningProgressService.selectList(learningProgressWrapper);

        for (LearningProgressEntity lp : learningProgressList) {
            Long userId = lp.getUserId();
            Integer progressSecondsInLesson = lp.getProgressSeconds();

            EntityWrapper<OverallProgressEntity> overallProgressWrapper = new EntityWrapper<>();
            overallProgressWrapper.eq("user_id", userId);
            overallProgressWrapper.eq("course_id", courseId);

            OverallProgressEntity overallProgress = overallProgressService.selectOne(overallProgressWrapper);

            if (overallProgress != null) {
                Integer oldUserOverallProgress = overallProgress.getUserOverallProgress();
                //用当前学习的总时间减去刚刚被改的那节课的学习时间
                overallProgress.setUserOverallProgress(oldUserOverallProgress - progressSecondsInLesson);
                //总时长设置成新的，上面算过
                overallProgress.setCourseOverallLength(course.getOverallVideoLength());

                Integer updatedCourseOverallLength = course.getOverallVideoLength();
                if (updatedCourseOverallLength == null || updatedCourseOverallLength <= 0) {
                    overallProgress.setProgressPercent(0f);
                } else {
                    float newProgressPercent = (float) overallProgress.getUserOverallProgress() / updatedCourseOverallLength * 100;
                    overallProgress.setProgressPercent((float)Math.round(newProgressPercent));
                }

                overallProgressService.updateById(overallProgress);
            } else {
                System.err.println("Warning: OverallProgress not found for userId: " + userId + ", courseId: " + courseId);
            }
        }
        learningProgressService.deleteByLessonId(lessonId);
    }
}
